// 本地存储数据库管理模块
class DatabaseManager {
    constructor() {
        this.isInitialized = false;
        this.storageKey = 'suzhou_travel_db';
    }
    
    // 初始化数据库
    async init() {
        try {
            // 初始化本地存储
            this.initLocalStorage();
            this.isInitialized = true;
            console.log('数据库初始化成功');
            return Promise.resolve();
        } catch (error) {
            console.error('数据库初始化失败:', error);
            throw error;
        }
    }
    
    initLocalStorage() {
        // 检查是否存在存储数据
        if (!localStorage.getItem(this.storageKey)) {
            const initialData = {
                routes: [],
                waypoints: [],
                itinerary: [],
                nextId: 1
            };
            localStorage.setItem(this.storageKey, JSON.stringify(initialData));
        }
    }
    
    // 获取存储数据
    getData() {
        const data = localStorage.getItem(this.storageKey);
        return data ? JSON.parse(data) : { routes: [], waypoints: [], itinerary: [], nextId: 1 };
    }
    
    // 保存存储数据
    saveData(data) {
        localStorage.setItem(this.storageKey, JSON.stringify(data));
    }
    
    // 保存路线
    async saveRoute(routeData) {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        const route = {
            id: data.nextId++,
            name: routeData.name || '未命名路线',
            start_name: routeData.start.name,
            start_coords: routeData.start.coordinates,
            end_name: routeData.end.name,
            end_coords: routeData.end.coordinates,
            waypoints: routeData.waypoints || [],
            total_distance: routeData.totalDistance || 0,
            total_duration: routeData.totalDuration || 0,
            total_cost: routeData.totalCost || 0,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            is_active: routeData.isActive || false
        };
        
        data.routes.push(route);
        this.saveData(data);
        
        return route.id;
    }
    
    // 获取所有路线
    async getRoutes() {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        return data.routes.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    }
    
    // 获取活跃路线
    async getActiveRoute() {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        return data.routes.find(route => route.is_active) || null;
    }
    
    // 设置活跃路线
    async setActiveRoute(routeId) {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        
        // 先取消所有活跃路线
        data.routes.forEach(route => {
            route.is_active = false;
        });
        
        // 设置指定路线为活跃
        const route = data.routes.find(r => r.id === routeId);
        if (route) {
            route.is_active = true;
            route.updated_at = new Date().toISOString();
        }
        
        this.saveData(data);
    }
    
    // 删除路线
    async deleteRoute(routeId) {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        
        // 删除相关途经点
        data.waypoints = data.waypoints.filter(wp => wp.route_id !== routeId);
        
        // 删除路线
        data.routes = data.routes.filter(route => route.id !== routeId);
        
        this.saveData(data);
    }
    
    // 更新路线
    async updateRoute(routeId, routeData) {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        const route = data.routes.find(r => r.id === routeId);
        
        if (route) {
            route.name = routeData.name || '未命名路线';
            route.start_name = routeData.start.name;
            route.start_coords = routeData.start.coordinates;
            route.end_name = routeData.end.name;
            route.end_coords = routeData.end.coordinates;
            route.waypoints = routeData.waypoints || [];
            route.total_distance = routeData.totalDistance || 0;
            route.total_duration = routeData.totalDuration || 0;
            route.total_cost = routeData.totalCost || 0;
            route.updated_at = new Date().toISOString();
            
            this.saveData(data);
        }
    }
    
    // 保存行程数据
    async saveItinerary(itineraryData) {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        
        // 清空现有行程
        data.itinerary = [];
        
        // 添加新行程
        itineraryData.forEach(item => {
            data.itinerary.push({
                id: data.nextId++,
                name: item.name,
                time: item.time,
                description: item.description,
                coords: item.coordinates,
                type: item.type,
                status: item.status,
                created_at: new Date().toISOString()
            });
        });
        
        this.saveData(data);
    }
    
    // 获取行程数据
    async getItinerary() {
        if (!this.isInitialized) {
            throw new Error('数据库未初始化');
        }
        
        const data = this.getData();
        return data.itinerary.sort((a, b) => a.time.localeCompare(b.time));
    }
}

// 创建全局数据库实例
window.dbManager = new DatabaseManager();
